package org.liang.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
import io.seata.spring.annotation.GlobalTransactional;
import org.liang.clients.AuthClient;
import org.liang.clients.CommonClient;
import org.liang.domain.Employee;
import org.liang.domain.LoginUser;
import org.liang.domain.Tenant;
import org.liang.domain.TenantMeal;
import org.liang.dto.TenantRegisterDto;
import org.liang.exception.BusinessException;
import org.liang.exception.ResponseCode;
import org.liang.exception.RonghuaAssert;
import org.liang.mapper.TenantMapper;
import org.liang.service.IEmployeeService;
import org.liang.service.ITenantMealService;
import org.liang.service.ITenantService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.liang.util.AjaxResult;
import org.liang.util.encrypt.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liang
 * @since 2024-05-29
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private AuthClient authClient;

    @Autowired
    private CommonClient commonClient;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private ITenantMealService tenantMealService;

    /**
     * 租户入驻
     *
     * @param dto
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void tenantRegister(TenantRegisterDto dto) {
        //参数校验
        //两次密码是否一致
        Employee admin = dto.getAdmin();
        RonghuaAssert.isEq(admin.getPassword(), admin.getConfirmPassword(), ResponseCode.RESPONSE_CODE_400001);

        //店铺是否被注册（根据名字）
        Tenant tenantInDb = selectOne(new EntityWrapper<Tenant>().eq("company_name", dto.getCompanyName()));
        RonghuaAssert.isNull(tenantInDb, ResponseCode.RESPONSE_CODE_400002);
        //管理员信息已存在
        Employee employee = employeeService.selectOne(new EntityWrapper<Employee>().eq("tel", admin.getTel()));
        RonghuaAssert.isNull(employee, ResponseCode.RESPONSE_CODE_400003);

        //店铺名字合法性

        //保存管理员信息到employee表
        //保存登录信息
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(admin.getUsername());
        //加盐加密
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        loginUser.setSalt(salt);
        String password = MD5.getMD5("gift" + salt + admin.getPassword());
        loginUser.setPassword(password);
        loginUser.setTel(admin.getTel());
        loginUser.setEmail(admin.getEmail());
        loginUser.setType(LoginUser.ADMIN_PLATFORM);
        AjaxResult ajaxResult = authClient.addOrUpdate(loginUser);
        if (!ajaxResult.getSuccess()) {
            throw new BusinessException(ajaxResult.getMsg());
        }

        //保存员工信息
        admin.setState(Employee.STATE_LOCK);
        admin.setType(Employee.PLATFORM_ADMIN);
        admin.setInputTime(new Date());
        employeeService.insert(admin);

        //保存店铺信息
        Tenant tenant = new Tenant();
        tenant.setAddress(dto.getAddress());
        tenant.setCompanyName(dto.getCompanyName());
        tenant.setCompanyNum(dto.getCompanyNum());
        tenant.setRegisterTime(new Date());
        tenant.setLogo(dto.getLogo());
        tenant.setAdminId(admin.getId());
        tenant.setState(Tenant.STATE_WAIT_AUDIT);
        insert(tenant);

        //保存套餐信息
        List<Long> meals = dto.getMealIds();
        List<TenantMeal> list = new ArrayList<>();
        for (Long mealId : meals) {
            list.add(new TenantMeal(mealId, tenant.getId(), null, 0));
        }
        tenantMealService.insertBatch(list);

        //发送邮件
        commonClient.sendQQEmail("2256565379@qq.com", 0);
    }

    //激活邮件
    @Override
    public void activation(String emailName) {
        Employee employee = employeeService.selectOne(new EntityWrapper<Employee>().eq("email", emailName));
        Tenant tenant = selectOne(new EntityWrapper<Tenant>().eq("admin_id", employee.getId()));
        tenant.setState(Tenant.STATE_ACTIVE_SUCCESS);
        updateById(tenant);
    }

    //店铺入驻审核通过
    @Override
    public void reviewAdopt(Tenant tenant) {
        //更新审核状态
        tenant.setState(tenant.STATE_WAIT_ACTIVE);

        //邮件内容可能用到
        //Shop shop1 = shopMapper.queryEmployeeByShopId(shop.getId());

        //存在的问题---发送邮件不需要立即生效-----解决--将消息放入到消息队列中  @ToDo

        //发送邮件
        commonClient.sendQQEmail("2256565379@qq.com", 1);

        updateById(tenant);
    }

    //店铺入驻审核驳回
    @Override
    public void reviewReject(Tenant tenant) {
        tenant.setState(tenant.STATE_REJECT_AUDIT);
        //发送邮件
        commonClient.reviewReject("2256565379@qq.com",
                tenant.getQuestionData().getRegion(),
                tenant.getQuestionData().getDesc());

        updateById(tenant);
    }
}
